package com.hexu.event.view;

import com.hexu.event.bean.AttractionsBean;
import com.hexu.event.entity.Attractions;
import com.hexu.event.entity.Comment;
import com.hexu.event.entity.TicketHistory;
import com.hexu.event.entity.User;
import com.hexu.event.util.StageUtil;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.layout.GridPane;
import javafx.stage.Stage;

import java.util.Arrays;
import java.util.List;

import static com.hexu.event.util.ServiceUtil.*;
import static com.hexu.event.util.StageUtil.display;
import static com.hexu.event.view.AdministratorView.selectIndex;
import static com.hexu.event.view.VisitorsView.dateDisplay;


public class UserView {

    //本用户界面的用户手机号
    private static String userPhoneNumber;

    //存性别的选择
    private static String[] desc = new String[1];

    private static User user = new User();

    //获取user的信息
    public static void getUserInformation(String phoneNumber){

        userPhoneNumber = phoneNumber;
        user = userService.getAUser(phoneNumber,user);
    }

    public void userView(Stage primaryStage)throws Exception{
        //设置按钮
        Button searchAttractions = new Button("查看景点");
        Button backLogin= new Button("返回登录界面");
        Button personalInformation = new Button("个人信息");
        Button recharge = new Button("充值");
        Button ticketHistory = new Button("购票历史");

        //创建网格布局
        GridPane gridPane = new GridPane();
        //设置颜色
        gridPane.setStyle("-fx-background-color: #FFF5EE");

        //设置网格位置
        gridPane.add(searchAttractions,1,0);
        gridPane.add(backLogin,2,0);
        gridPane.add(personalInformation ,1,1);
        gridPane.add(recharge,2,1);
        gridPane.add(ticketHistory,2,2);

        //设置水平间距
        gridPane.setHgap(35);
        //设置垂直间距
        gridPane.setVgap(40);

        //进行对齐
        gridPane.setAlignment(Pos.CENTER);

        //调用工具类的方法显示界面
        StageUtil.showStage(primaryStage,new Scene(gridPane),500,500,"用户界面",false);

        //设置 查看景点 单击事件
        searchAttractions.setOnAction(new EventHandler<ActionEvent>() {
            @Override
            public void handle(ActionEvent event) {
                //取出景点的所有信息
                List<Attractions> listAttractionsAllInformation = attractionsService.getAttractionsInformation();
                //取出景点数量
                int attractionsCount = attractionsService.attractionsNumber();
                administratorView.view(primaryStage,1,userPhoneNumber,attractionsCount,listAttractionsAllInformation);
                 }
        });

        //设置 充值 的单击事件
        recharge.setOnAction(new EventHandler<ActionEvent>() {
            @Override
            public void handle(ActionEvent event) {
                toRecharge();
            }
        });

        //设置 返回登录界面 单击事件
        backLogin.setOnAction(new EventHandler<ActionEvent>() {
            @Override
            public void handle(ActionEvent event) {
                primaryStage.close();
                LoginInView loginInView = new LoginInView();
                try {
                    loginInView.start(primaryStage);
                }catch (Exception ex){
                    ex.printStackTrace();
                }
            }
        });

        //设置 个人信息 单击事件
        personalInformation.setOnAction(new EventHandler<ActionEvent>() {
            @Override
            public void handle(ActionEvent event) {
                toPersonalInformation();
            }
        });

        //设置 购票历史 单击事件
        ticketHistory.setOnAction(new EventHandler<ActionEvent>() {
            @Override
            public void handle(ActionEvent event) {
                toTicketHistory();
            }
        });

    }

    //充值的实现方法
    private static void toRecharge(){
        //本次充值的数量
        final int[] number = {0};

        //可选择的充值金额
        RadioButton radioButton1 = new RadioButton("100");
        RadioButton radioButton2 = new RadioButton("300");
        RadioButton radioButton3 = new RadioButton("600");

        Button button = new Button("确定");

        GridPane gridPane = new GridPane();

        //设置位置
        gridPane.add(radioButton1,0,1);
        gridPane.add(radioButton2,1,1);
        gridPane.add(radioButton3,2,1);
        gridPane.add(button,2,2);

        //设置间隔和位置
        gridPane.setVgap(15);
        gridPane.setHgap(15);
        gridPane.setAlignment(Pos.CENTER);

        //设置单选及其值
        ToggleGroup group = new ToggleGroup();
        radioButton1.setToggleGroup(group);
        radioButton1.setUserData(100);
        radioButton2.setToggleGroup(group);
        radioButton2.setUserData(300);
        radioButton3.setToggleGroup(group);
        radioButton3.setUserData(600);


        Stage primaryStage = new Stage();

        //调用工具类的方法显示界面
        StageUtil.showStage(primaryStage,new Scene(gridPane),170,250,"充值",false);

        //设置 确定 的单击事件
        button.setOnAction(new EventHandler<ActionEvent>() {
            @Override
            public void handle(ActionEvent event) {
                //更新一波数据
                getUserInformation(userPhoneNumber);

                //勾选了充值金额
                if(number[0] != 0){
                    //传入数据
                    user.setSystemBalance(number[0]+Integer.valueOf(user.getSystemBalance()));
                    user.setPhoneNumber(user.getPhoneNumber());

                    userService.addSystemBalance(user);

                    //充值成功的消息提示
                    Alert alert = new Alert(Alert.AlertType.CONFIRMATION);
                    alert.setTitle("消息");
                    alert.setHeaderText("充值成功！（所充金额均来自花呗）");
                    alert.showAndWait();
                    primaryStage.close();

                }else{

                    Alert alert = new Alert(Alert.AlertType.INFORMATION);
                    alert.setTitle("消息");
                    alert.setHeaderText("请先勾选金额！");
                    alert.showAndWait();
                }

            }
        });


        // 选中某个单选框时输出选中的值
        group.selectedToggleProperty().addListener(
                new ChangeListener<Toggle>() {
                    public void changed(
                            ObservableValue<? extends Toggle> ov,
                            Toggle old_toggle, Toggle new_toggle) {
                        if (group.getSelectedToggle() != null) {

                        number[0] = (int) group.getSelectedToggle().getUserData();

                        }
                    }
                });
    }

    //查看用户自己的信息
    private static void toPersonalInformation(){
        //更新数据
        user = userService.getAUser(userPhoneNumber,user);
        //设置标签
        Label labelPhoneNumber = new Label("账号:"+user.getPhoneNumber());
        Label labelUserName = new Label("用户名:"+user.getUserName());
        Label labelSex = new Label("性别:"+user.getSex());
        Label labelBalance = new Label("余额:"+user.getSystemBalance());
        Label labelState = new Label("状态："+user.getFreeze());
        Label labelDeblocking = new Label("解封时间:"+user.getDeblocking());

        Button update = new Button("修改信息");
        GridPane gridPane = new GridPane();

        //设置标签位置
        gridPane.add(labelPhoneNumber,0,0);
        gridPane.add(labelUserName,0,1);
        gridPane.add(labelSex,0,2);
        gridPane.add(labelBalance,0,3);
        gridPane.add(labelState,0,4);
        gridPane.add(labelDeblocking,0,5);
        gridPane.add(update,0,6);

        //设置距离
        gridPane.setAlignment(Pos.CENTER);
        gridPane.setHgap(15);
        gridPane.setVgap(15);

        Stage stage = new Stage();

        //调用工具类的方法显示界面
        StageUtil.showStage(stage,new Scene(gridPane),500,400,"个人信息",false);

        //设置 修改信息 的单击事件
        update.setOnAction(new EventHandler<ActionEvent>() {
            @Override
            public void handle(ActionEvent event) {
                //界面关闭
                stage.close();
                updateUserInformation();
            }
        });

    }

    //修改用户信息
    public static void updateUserInformation(){
        //更新数据
        user = userService.getAUser(userPhoneNumber,user);
        //设置标签和文本框
        Label labelPhoneNumber = new Label("账号:");
        Label labelPassword = new Label("密码");
        Label labelUserName = new Label("用户名:");
        Label labelSex = new Label("性别:");
        Label labelBalance = new Label("余额:");
        TextField phoneNumber = new TextField(user.getPhoneNumber()+"(不可修改)");
        phoneNumber.setEditable(false);
        TextField password = new TextField(user.getPassword());
        TextField userName = new TextField(user.getUserName());
        TextField balance = new TextField(user.getSystemBalance()+"(不可修改)");
        balance.setEditable(false);

        Button update = new Button("确定修改");

        //创建网格布局
        GridPane gridPane = new GridPane();
        //设置颜色
        gridPane.setStyle("-fx-background-color: #FFF5EE");

        // 初始化性别列表
        List<String> snackList = Arrays.asList("男", "女", "未知性别");
        // 把清单对象转换为JavaFX控件能够识别的数据对象
        ObservableList<String> obList = FXCollections.observableArrayList(snackList);
        // 依据指定数据创建下拉框
        ComboBox<String> comboBox = new ComboBox<String>(obList);
        //开始默认获取性别
        desc[0] = user.getSex();
        if(desc[0].equals("男")){
            // 设置下拉框默认选中第1项
            comboBox.getSelectionModel().select(0);
        }else if(desc[0].equals("女")){
            // 设置下拉框默认选中第2项
            comboBox.getSelectionModel().select(1);
        }else{
            // 设置下拉框默认选中第3项
            comboBox.getSelectionModel().select(2);
        }

        // 设置下拉框能否编辑。默认不允许编辑
        comboBox.setEditable(false);

        // 设置下拉框的选择监听器
        comboBox.getSelectionModel().selectedItemProperty().addListener(new ChangeListener<String>() {
            @Override
            public void changed(ObservableValue<? extends String> arg0, String old_str, String new_str) {
                // getSelectedIndex方法可获得选中项的序号，getSelectedItem方法可获得选中项的对象
                desc[0] = comboBox.getSelectionModel().getSelectedItem();
            }
        });

        //设置网格位置
        gridPane.add(labelPhoneNumber,0,0);
        gridPane.add(phoneNumber,1,0);
        gridPane.add(labelPassword,0,1);
        gridPane.add(password,1,1);
        gridPane.add(labelUserName,0,2);
        gridPane.add(userName,1,2);
        gridPane.add(labelSex,0,3);
        gridPane.add(comboBox,1,3);
        gridPane.add(labelBalance,0,4);
        gridPane.add(balance,1,4);
        gridPane.add(update,1,5);

        //设置水平间距
        gridPane.setHgap(5);
        //设置垂直间距
        gridPane.setVgap(15);

        //进行中间对齐
        gridPane.setAlignment(Pos.CENTER);

        Stage primaryStage = new Stage();
        StageUtil.showStage(primaryStage,new Scene(gridPane),500,800,"用户修改信息",false);

        //设置单击事件 确定修改
        update.setOnAction(new EventHandler<ActionEvent>() {
            @Override
            public void handle(ActionEvent event) {
                //把修改的数据传给User
                user.setUserName(userName.getText());
                user.setSex(desc[0]);
                user.setPassword(password.getText());

                userService.updateUser(user);

               display(true,primaryStage,"修改信息");
            }
        });

    }


    //查看用户自己的购票历史
    private static void toTicketHistory(){

        //获得这个用户的购票历史
        List<TicketHistory> ticketHistory = ticketHistoryService.getAUserTicketHistory(userPhoneNumber);
        //获得用户购买的门票数
        int ticketNumber = ticketHistoryService.aUserTicketNumber(userPhoneNumber);
        ticketHistoryTableView.viewTicketHistoryInformation(ticketNumber,ticketHistory );
    }

    public static void commentSure(String textFieldComment,String attractionName){
        //保存评论
        Comment comment = new Comment(null,userPhoneNumber,attractionName,textFieldComment,dateDisplay());

        //把该景点所有信息传入
        Attractions attractions = attractionsService.getAttraction(attractionName);
        attractions.setCommentNumber(attractions.getCommentNumber()+1);
        attractionsService.commentAttractions(attractions);

        display(commentService.addComment(comment),new Stage(),"评论");

    }

    public static void buy(String phoneNumber,String attractionName,TableView table){
        //传入用户的手机号、景点的名字，票价，票数、景点id
        buyTicket(phoneNumber,attractionName,table,selectIndex);

    }

    //设置用户购票
    public static void buyTicket(String phoneNumber,String selectName,TableView table,int selectIndex){
        //获得用户数据
        user = userService.getAUser(phoneNumber,user);
        //把该景点所有信息传入
        Attractions attractions = attractionsService.getAttraction(selectName);

        //余额足够支付并且有票多余并且没冻结
        if((user.getSystemBalance()-attractions.getTicketFare())>=0
                &&attractions.getTicketNumber()>0 && user.getFreeze().equals("解封")){
            //传入数据
            //传入user的余额,其它值不变
            user.setSystemBalance(user.getSystemBalance()-attractions.getTicketFare());
            //修改余额
            userService.addSystemBalance(user);

            //传入门票数-1,其它不变
            attractions.setTicketNumber(attractions.getTicketNumber()-1);
            attractions.setName(attractions.getName());
            attractionsService.buyTicketAttractions(attractions);

            //传入购票历史的用户手机号码、购票时间、景点名字
            TicketHistory ticketHistory = new TicketHistory(null, user.getPhoneNumber(), dateDisplay(),
                    attractions.getName(),attractions.getTicketFare());
            ticketHistoryService.addTicketHistory(ticketHistory);
            StageUtil.display(true,new Stage(),"购票");

            //表格中门票数减一
            table.getItems().set(selectIndex,new AttractionsBean(attractions.getName(),attractions.getOpenTime(),attractions.
                    getTicketFare(),attractions.getTicketNumber(),attractions.getIntroduce(),attractions.getCommentNumber()));

        }else if(attractions.getTicketNumber()<=0){
            Alert alert = new Alert(Alert.AlertType.INFORMATION);
            alert.setTitle("消息");
            alert.setHeaderText("门票已售完，购票失败！");
            alert.showAndWait();
        }else if((user.getSystemBalance()-attractions.getTicketFare())<0){
            Alert alert = new Alert(Alert.AlertType.INFORMATION);
            alert.setTitle("消息");
            alert.setHeaderText("余额不足，购票失败！");
            alert.showAndWait();
        }else{
            Alert alert = new Alert(Alert.AlertType.INFORMATION);
            alert.setTitle("消息");
            alert.setHeaderText("账号被管理员冻结，购票失败！");
            alert.showAndWait();
        }

    }
}